/*
	Create Date : 
	Author    : Pham Van Dam
	Copyright(c) 2009 A.D.A Solution. All rights reserved
	=====================================================
	Update History:
	Ver.    TRB#        Date          Author       Note
	1		V001		2010/02/04	  Toannn	   Thêm chức năng cập nhật lại Phương tiện khi Tracking		
	2		V002		2010/03/09	  Toannn	   Thêm Tab biểu đồ, hiển thị trạng thái Phương tiện của User dó.	
    2.0     TRB003      2010/10/13    Tannd	        Fix bug zoom lớn nhất từ google chuyển qua VBD lỗi
*/
var hidedevice 	    = GLOBAL_HIDE_DEVICE;
var choosedevice 	= GLOBAL_CHOOSE_DEVICE;
var chosseTime      = GLOBAL_CHOOSE_TIME;
var number			= GLOBAL_NUMBER;
var chooseFromday	= GLOBAL_CHOOSE_FROM_DATE;
var chooseToday		= GLOBAL_CHOOSE_TO_DATE;
var strtime			= GLOBAL_TRKTIME;
var strstatus		= GLOBAL_TRKSTATUS;
var l				= GLOBAL_LOCATION;
var stopfor 	    = GLOBAL_STOP_FOR;
var lostfor 	    = GLOBAL_LOST_FOR;
var gpsfor 		    = GLOBAL_GPS_FOR;
var running         = GLOBAL_RUNNING;
var numlimit        = GLOBAL_NUMLIMIT;
// ĐậmPV: 2010-10-12 - Add Start
var buffer          = GLOBAL_BUFFER;
// ĐậmPV: 2010-10-12 - Add End

function Global()
{
   
	var obj=new Object();	
	obj.countTime=1;
	obj.numTimeTracking=1;
	obj.numTimeReview=5; // gia tri mac dinh la 5s
	obj.currentDateReview;
	obj.fromDateReview;
	obj.toDateRevive;		
	obj.devReview=new Object();
	obj.devTracking=new Object();
	obj.arrDevicename =new Array();
	obj.arrDeviceAlert =new Array();
	obj.locs=new Object(); // đối tượng địa diểm
	
	////////////////////////////////
	//////Tannd
	obj.checkTracking=false;
	obj.checkLoadDevice=false;
	obj.checkPlayReview=false;
	obj.checkChooseDevice=true;
	obj.checkMap=0;	// ĐậmPV: 2010-10-27 - Edit: 0: GMaps, 1: Vietbando, 2: vnGeoBiz, 3:wikimapia
    obj.gMap;
    obj.vMap;
    obj.wMap;
    obj.myMap=new Object();
	obj.listenerAddLoc;
	obj.checkListener=false;
	obj.TabSelect=0;
	obj.StatusStartReview=0;
	var timein;
	var arrDateReview= new Array();
	obj.arrcheckbox = new Array(true,true,true,true,true);  // ĐậmPV: 2010-10-12 - Edit: buffer
	
	//1 V002  2010-03-09  Toannn  Thêm vào biến sử lý cho Biểu đồ  Edit Start
	obj.data=""; 									// dư liệu của Biểu đồ
	obj.indexTabBottom=0;							// luu trang thai tab phía dưới
	obj.arrStatus= new Array();                  // Mãng đếm trạng thái các Phương tiện.
	//1 V002  2010-03-09  Toannn  Thêm vào biến sử lý cho Biểu đồ  Edit Start
	
	var fromday;
    var today;
    var fromtime;
    var totime;
	var nSumDate=0;
    //////////////////
    obj.indexGP6000 = 0;
    obj.GP6000Interval = 5; // 5 giây
    obj.GP6000Timer = 0;
    obj.trackingDeviceID = 0;
    obj.trackingDeviceName = '';
    obj.trackingIMEI = '';
		
    obj.InitMap=function(div,checkMap)
    {

        if(obj.checkMap==checkMap)
            return;		
        
        var container=document.getElementById(div); 
        container.innerHTML=''; 
		
		try{
			if(typeof(obj.listenerAddLoc)!='undefined' && obj.listenerAddLoc!=null)
				obj.myMap.RemoveOnClick(obj.listenerAddLoc);
		}catch(err){
			alert(err);
		}
				
        if(checkMap==0)	// Google maps
        {   
            document.getElementById('mapType').value =0;// trung add
            document.getElementById('distanceValue').value =0; // trung add
            if(obj.checkMap != 0)
            {
                try{                   
                 obj.vMap.UnloadMap();      // trung add         
                }catch(err){};
               var center = obj.myMap.GetCenter();
		       var level=obj.myMap.GetLevel();
               obj.gMap.InitMap(div, 0);	// Chỉ có google maps
               obj.myMap=obj.gMap;
               
               //thiet lap lai do zoom
               if(obj.checkMap == 1)
		            obj.myMap.ZoomTo(center.latitude,center.longitude,obj.V2G(level));	
               else if(obj.checkMap == 2)
                    obj.myMap.ZoomTo(center.latitude,center.longitude,level);
               
            }
        }
		else if(checkMap == 1)	// Vietbando 
        {
            document.getElementById('mapType').value =1;// trung add
            document.getElementById('distanceValue').value =0; // trung add
            if(obj.checkMap != 1)
            {
                try{                    
                    obj.gMap.UnloadMap();           
                }catch(err){};
			    var level=obj.myMap.GetLevel();
                obj.vMap.InitMap(div,1); 
                obj.myMap=obj.vMap;
                //thiet lap lai do zoom			            
		       obj.myMap.ZoomTo(obj.gMap.GetCenter().latitude,obj.gMap.GetCenter().longitude,obj.G2V(level));
            }
			
        }else
		{
            if(obj.checkMap != 2)
            {
			    // vnGeoBiz
                var center = obj.myMap.GetCenter();
			    var level=obj.myMap.GetLevel();
			    obj.gMap.InitMap(div, 1);	// Google maps với vngeobiz
			    obj.myMap=obj.gMap;
            }
		}
		
		//Cap nhat lai su kien ve location
        obj.checkMap=checkMap;
        if(obj.TabSelect==0)
        {
            obj.devTracking.CreateIconAll(0);
            obj.devTracking.CreateIconAll2(0);
        }
        else
        {            
            obj.devReview.CreateIconAll(1);            
            obj.devReview.CreateIconLineReview();
        }
        obj.locs.CreateAll();
        
        try{
        
        obj.AddLocation(obj.checkListener);
        }catch(err)
        {
            alert(err);
        }
    }
    obj.G2V=function(level)
    {  
      // TRB003 start add
      if(level>19)
      {
          level=19;
      }
      //TRB003 End add              
      return level;
    }
    obj.V2G=function(level)
    {
      //  max 20
      //  var result=level+5;
      //  if(result>20)
      //      result=20;
     
        return level;
    }  
	
	
	
	var timePlay=1;
	obj.ClearArrayReView=function()
	{
		obj.devReview.arrDevice="";
		document.getElementById("btnPlay").innerHTML="";
	}
	obj.play=function(bCheck)		//Review autoplay
	{
        if(bCheck && $('#flagDistance').val()==1){
            setFlagDistance();
        }
	    obj.checkPlayReview=bCheck;
		obj.numTimeReview=obj.ValueElement("numTimeReview");
		if (obj.devReview.lengthArr>0)
		{
			if(bCheck == true)	//Neu bieu tuong la play (dang dung)
			{		
				if(obj.checkTracking==true)
				{
					obj.StartTracking(false);   // Dung Tracking khi dang xem ReView
				}
				document.getElementById("btnPlay").src='images/stopbut.png';
                $('#btnPlay').attr('title', 'Nhấn để dừng xem mô phỏng');    
				obj.devReview.ClearLineReview(); // xóa đường Review
                 obj.myMap.HideInfo();
                $('#chkFlgPaint').attr('disabled','disabled');
                document.getElementById('hdMoveEnd').value = 1;
                if(obj.numTimeReview <= 0 || obj.numTimeReview > 99)
                {
                    alert(chosseTime);
                    return;
                }
                var newl = document.getElementById('hdZoomto').value;
                if ($('#chkFlgPaint').val() == 3 && newl < 16)
                {
                   $('#hdPlayZoom').val(1); 
                }
                else
                {
                   $('#hdPlayZoom').val(0);  
                }                     
				if(obj.numTimeReview > 0)
				{					
					if(obj.devReview.currentIndex <= obj.devReview.lengthArr)
					{
                       for(var i  in obj.devReview.arrDevice)
                        {
                            if($('#chkFlgPaint').val() == 0 || $('#chkFlgPaint').val() == 2  
                            || ($('#chkFlgPaint').val() == 3 && newl >= 16) || ($('#chkFlgPaint').val() == 3 && newl < 16 && obj.devReview.arrDevice[i].status == 1) || ($('#chkFlgPaint').val() == 1 && obj.devReview.arrDevice[i].status == 1))
                             {   
                                   obj.myMap.HideIcon(obj.devReview.arrDevice[i].icon);  
                             }
                        } 
                        obj.IsFinishPlaying = false;                         				
						obj.tickerPlay();
					}
				}
			}
			else	//Neu la dang chay
			{				
                obj.IsPlaying = false;
                obj.IsFinishPlaying = true;
				document.getElementById("btnPlay").src='images/playbut.png';
                $('#btnPlay').attr('title', 'Nhấn để xem mô phỏng');				
				clearTimeout(timein);
				timePlay = 0;
				obj.StatusStartReview=0;
                $('#chkFlgPaint').removeAttr('disabled');
                document.getElementById('hdMoveEnd').value = 0;
			}
		}	
		else
		{
			obj.StatusStartReview=0;
		}
	}
    obj.IsFirstPlay = false;
    obj.IsPlaying = false;
    obj.IsFinishPlaying = true;    
	obj.tickerPlay=function()
	{
		try
		{
			//Neu chua toi diem cuoi cung thi chay tiep, nguoc lai, dung 
			if(obj.devReview.currentIndex <= obj.devReview.lengthArr)
			{
                obj.IsPlaying = true;
                if (!obj.IsFirstPlay)
                {
                    obj.devReview.currentIndex = obj.devReview.currentIndex - 1;
                    obj.IsFirstPlay = true;
                }
                
				obj.devReview.NextView();
				timein=window.setTimeout("_global.tickerPlay()",obj.numTimeReview*1000);
                
                if (obj.devReview.currentIndex == obj.devReview.lengthArr)				
                {
                    obj.myMap.ClearDrawRun();  
                    obj.IsPlaying = false;
                    obj.IsFinishPlaying = true;                                                  
                    obj.checkPlayReview = false;
                    document.getElementById("btnPlay").src='images/playbut.png';
                    $('#btnPlay').attr('title', 'Nhấn để xem mô phỏng');
                    window.clearTimeout(timein);
                    obj.StatusStartReview=0;
                    timein = 0;
                    $('#chkFlgPaint').removeAttr('disabled');
                    document.getElementById('hdMoveEnd').value = 0;
                }
			}
			else
			{
               
                obj.IsPlaying = false;
				obj.devReview.currentIndex=0;  
				obj.checkPlayReview=false;
				document.getElementById("btnPlay").src='images/playbut.png';
                $('#btnPlay').attr('title', 'Nhấn để xem mô phỏng');
				window.clearTimeout(timein);
				obj.StatusStartReview=0;
				timein = 0;
                $('#chkFlgPaint').removeAttr('disabled');
                document.getElementById('hdMoveEnd').value = 0;				
			}			
		}	
		catch(e)	
		{
			alert(e);		
		}
	}
	obj.CenterReSize=function()
	{	
		var hCenter=document.getElementById("divCenter").offsetHeight;
		var htabs=parseInt(document.getElementById("divTabs").offsetHeight);
        var hDemoTip = parseInt(document.getElementById("demotip").offsetHeight);
        
        // Start - Set hight for the Tab Tracking
        var hStatusTracking=parseInt(document.getElementById("status-tracking").offsetHeight);
        hStatusTracking = (hStatusTracking == 0) ? 20 : hStatusTracking;
        
        var hTopTracking=parseInt(document.getElementById("top-tracking").offsetHeight);
        hTopTracking = (hTopTracking == 0) ? 59 : hTopTracking;
        
        var htckingGrid = hCenter - hDemoTip - hTopTracking - hStatusTracking - htabs;
        htckingGrid = htckingGrid - 20;
                if (htckingGrid < 0)
        {
           htckingGrid = 0; 
        }
        document.getElementById("tbl-list-tracking").style.height =htckingGrid+"px";
        document.getElementById("MenuString").style.height = htckingGrid + 40 + "px";
        // Start - Set hight for the Tab Tracking
        
        // Start - Set hight for the Tab Review
        var hTopReview = 145;
        if (document.getElementById("dvReViewTracking").style.display == 'none') 
        {
            hTopReview = 61;
        }
        var hReviewGrid = hCenter - hDemoTip - htabs - hTopReview;
        hReviewGrid = hReviewGrid - 20;
        if (hReviewGrid < 0)
        {
           hReviewGrid = 0; 
        }
        document.getElementById("tbl-list-review").style.height = hReviewGrid+"px";
        // End - Set hight for the Tab Review        
	}

	obj.ShowChooseDevice = function(idDiv,bCheck)
	{
		obj.checkChooseDevice=bCheck;
		if(bCheck == true)
		{
			document.getElementById(idDiv).style.display = ""; 
			obj.CenterReSize();
			document.getElementById('showButton').innerHTML=hidedevice;
		}	
		else
		{			
			document.getElementById(idDiv).style.display = "none";
			obj.CenterReSize();
			document.getElementById('showButton').innerHTML=choosedevice;
		}	
	}

	obj.StartTracking = function(bCheck)
	{   
        // Khi click Button Stop (bCheck = false) thi tat Canh Bao Tat Am Thanh
        if (!bCheck) {
            obj.StopMediaAlert();
        }
        
		obj.numTimeTracking=obj.ValueElement("txtnumTimeTracking");
	    obj.checkTracking=bCheck;
        
		if(obj.timerTracking>0)
		{
			window.clearTimeout(obj.timerTracking);
			obj.timerTracking = 0;	
		}				
				
		if(isNaN(obj.numTimeTracking))
		{
			alert(number);
		}
		else
		{
			obj.countTime=obj.numTimeTracking;
			if(obj.numTimeTracking<30)
			{
				alert(numlimit);
			}
			else
			{
				obj.SetValueElement("txtcountTime",obj.countTime);
				if(bCheck == true)
				{   
					obj.InitTracking();
				}
				else
				{
                    //obj.Review();
//					document.getElementById("startTracking").src="adagps.com/images/starttracking_"+sLang+".gif"; // Nut chuyen sang "Bat dau"
                     document.getElementById('btnStopTracking').style.display='none';//btnStartTracking
                     document.getElementById('btnStartTracking').style.display='';
					window.clearTimeout(obj.timerTracking); // Clear Time Out
					obj.timerTracking = 0;			
				}
			}	
		}
	}
    
    obj.InitTracking = function()
    {
        if(obj.checkPlayReview==true)
        {
            obj.play(false); // dung Review
        }
        obj.TabSelect = 0;
        obj.myMap.HideInfo(); // xoa cac Info tren ban do dang co                            
        obj.devReview.ClearAll(); // Xoa Review tren ban do 
        obj.devReview.ClearLineReview(); // xóa đường Review
//        document.getElementById("btnStartTracking").
//        document.getElementById('btnStartTracking').style.display='none';
//        document.getElementById("btnStartTracking").text = "Dừng";
        document.getElementById('btnStopTracking').style.display='';//btnStartTracking
        document.getElementById('btnStartTracking').style.display='none';
        //document.getElementById("startTracking").src="adagps.com/images/Stoptracking_"+sLang+".gif"; // Nut chuyen sang "dung"
        obj.UpdateTracking(); // bat dau Tracking    
        obj.RunTimerTracking(); //Chay timer 
    }
    
    obj.InitReviewTracking = function() 
    {
        obj.TabSelect = 1;
        obj.myMap.HideInfo();
        obj.devTracking.ClearAll();
        obj.devTracking.ClearAll2();
        obj.devReview.CreateIconAll(1);
        obj.devReview.CreateIconLineReview();
    }
	obj.UpdateTracking = function()
	{
		obj.devTracking.LoadDB();
	}
	obj.RunTimerTracking = function()
	{
		if(obj.countTime<=0)
		{        
			obj.UpdateTracking();
			_global.devTracking.Status(-1);	
			obj.countTime=obj.numTimeTracking;
                       
		}
        else
        {		
            obj.countTime--;
            if (obj.countTime < 0) 
            {
                obj.countTime = 0;
            }   		       	   
        }
        obj.SetValueElement("txtcountTime",obj.countTime);
        obj.timerTracking = window.setTimeout("_global.RunTimerTracking()",1000); 
		
	}
	//1 V001  2010/01/12  Toannn  thêm vào hàm TrackingTimes()  Edit Start
	/**
	 * Hàm TrackingTimes gọi hàm LoadTimes của device cho phép cập nhật lại dòng Highlight
	 */
	obj.TrackingTimes=function()
	{
		obj.devTracking.LoadTimes();	
	}
	//1 V001  2010/01/12  Toannn  thêm vào hàm TrackingTimes()  End Start
	obj.GetNameAlert=function()
	{
		xajax_ajxGetListDeviceAlert();
	}
    
    // Add-Start by Lamdhn: YC101 - 2011.04.05 
	obj.AddLocation = function(bCheck) {
        obj.checkListener = bCheck;
		if (bCheck) {
            document.getElementById('dvLocAddOption').style.display = '';  
            if (document.getElementById('rdLocRec').checked) {
                obj.AddLocByRec();
            } else {                
                obj.AddLocBySquares();
            }
		} else {
            document.getElementById('rdLocSquares').checked = true;
            obj.RemoveLocBySquares();
            obj.RemoveLocByRec();
            
            document.getElementById('dvLocAddOption').style.display = 'none';
		}        
	}
    
    obj.AddLocOptionOnChanged = function() {
        var bCheck = document.getElementById('chkAddLoc').checked;
        
        obj.AddLocation(bCheck);
    }
    
    obj.IsAddLocByRec = false;
    obj.AddLocByRec = function() {
        if (!obj.IsAddLocByRec) {
            obj.IsAddLocByRec = true;
            
            obj.myMap.PolyDragControl.ondragend = obj.myMap.AddOnClickByRec;
            obj.myMap.PolyDragControl.enableTransMarker();
                        
            obj.RemoveLocBySquares();
        } 
    }
    
    obj.RemoveLocByRec = function() {
        if (obj.IsAddLocByRec) {
            obj.IsAddLocByRec = false;
                       
            if (obj.myMap.PolyDragControl) {
                obj.myMap.PolyDragControl.reset();
                obj.myMap.PolyDragControl.disableTransMarker();
            }
            
            obj.myMap.HideInfo();
        }
    }
    
    obj.IsAddLocBySquares = false;
    obj.AddLocBySquares=function() {
        if (!obj.IsAddLocBySquares) {
            obj.IsAddLocBySquares = true;
            
            obj.listenerAddLoc=obj.myMap.AddOnClick();
            obj.RemoveLocByRec(); 
        }
    }
    
    obj.RemoveLocBySquares = function() {
        if (obj.IsAddLocBySquares) {
            obj.IsAddLocBySquares = false;
            obj.myMap.HideInfo();
            
            if (obj.myMap.locCreating) {
                obj.myMap.DeleteLocation(obj.myMap.locCreating);    
            }        
            
            if(typeof(obj.listenerAddLoc)!='undefined' && obj.listenerAddLoc!=null) {
                obj.myMap.RemoveOnClick(obj.listenerAddLoc);
            }
        }
    }
    // Add-End by Lamdhn: YC101 - 2011.04.05
        
	obj.ValueElement = function(idDiv)
	{
		 return (document.getElementById(idDiv).value);
	}
	obj.SetValueElement = function(idDiv,value)
	{
		 document.getElementById(idDiv).value=value;
	}
	obj.selectChange =function(idSelect)
	{   
	    if(obj.GetIndexCombobox(idSelect)>"0")
	    {
	        document.getElementById("FromDate").readOnly =true;
	        document.getElementById("ToDate").readOnly =true;
	        document.getElementById("imgcal1").style.display ="none";
	        document.getElementById("imgcal2").style.display ="none";
	    }
	    else
	    {
	        document.getElementById("FromDate").readOnly =false;
	        document.getElementById("ToDate").readOnly =false;
	        document.getElementById("imgcal1").style.display ="";
	        document.getElementById("imgcal2").style.display ="";
	    }
	}		
	obj.GetDevice=function()
	{
        xajax_ajxGetDeviceName();
	}
    obj.WriteComboDevice=function()
    {
        var sHTML="";
//        if (obj.arrDevicename.length > 0)
//        {        
        sHTML+="<select id='selectDev' style='width: 150px'>";
        for(var i=0;i<obj.arrDevicename.length;i++)
        {
            sHTML+="<option id='"+obj.arrDevicename[i].id+"' value='"+obj.arrDevicename[i].id+"'> "+obj.arrDevicename[i].name +" </option>"
        }
        sHTML+="</select>";
//        }
        //else 
//        {
//         sHTML+= '<span style="color:red">Không có Phương tiện</span>';   
//        }
        obj.InnerHtmlElement("dvdeviceReView",sHTML);
    }
    obj.InnerHtmlElement=function(idDiv,value)
    {
        document.getElementById(idDiv).innerHTML=value;
    }
	/**
	 * Hàm gán giá trị cần hiển thị cho combobox
	 */
	obj.SetSelectedIndex=function(name,index)
	{
		document.getElementById(name).selectedIndex=index;	
	}
    obj.SetValueForCombobox=function(cboName,value)
    {
        document.getElementById(cboName).value=value;    
    }
	obj.GetCheckbox=function(name)
	{
		var check =document.getElementById(name);
		if(check)
		{
			if(check.checked==true)
				return 1;
			else
				return 0; 
		}
        else
        {
            return 1;
        }
		
		return 0; 
	}
	obj.ShowDeviceFilter=function(bCheck)
	{
		if(bCheck==true)
		{
			document.getElementById("dvReViewTracking").style.display = ""; 
		}
		else 
		{
			document.getElementById("dvReViewTracking").style.display = "none"; 
		}
	}
	obj.ReView=function()
	{
		 // Kiem tra Combobox Tuy Chon
        obj.IsFinishPlaying = true;  
	    var index=obj.GetIndexCombobox("FromTimeReView");
		obj.StatusStartReview=1;
	    
	    if (index=="0")  // truong hop chon ngay theo lich
	    {
		    //Lay thong tin form o day.
		    fromday=document.getElementById("FromDate").value;
		    today=document.getElementById("ToDate").value;
            
            if(!objValidReView.CheckForm()) {
                alert(MSG_FROMDATE_NOT_FORMAT);
                return;
            }
            
            if (!CompareDateTime(fromday, today)) {
                alert(DATE_FROM_LESS_TO);
                document.getElementById('ToDate').focus();
                return;
            }
		    
		    fromday=obj.Replace(fromday);
		    today=obj.Replace(today);
		                            
		    var arrTemp= new Array();
		    var arrTemp2=new Array();
		    arrTemp=fromday.split(" ");
		    arrTemp2=today.split(" ");
		    
            if(obj.CheckDay(arrTemp[0])==false)
            {                 
                alert(chooseFromday);
                return;
            }        
            
            if(obj.CheckDay(arrTemp2[0])==false)
            {
                alert(chooseToday);
                return;
            }
            
            if (sLang == 'vi') {
                // Lay ngay gio va chuyen lai theo dung dinh dang
                fromday=obj.DMY2YMD(arrTemp[0]) ;
                fromtime=arrTemp[1];
                today=obj.DMY2YMD(arrTemp2[0]);
                totime=arrTemp2[1];
            } else { // sLang == 'en'
                // Lay ngay gio va chuyen lai theo dung dinh dang
                fromday=arrTemp[0]; // yyyy-MM-dd
                fromtime=arrTemp[1]; // HH:mm
                
                today=arrTemp2[0]; // yyyy-MM-dd
                totime=arrTemp2[1]; // HH:mm
            }
    	}
    	else  // truong hop chon Gio. Xu ly tinh toan lay lai FromDate va ToDate
    	{
    	   
            var tDate=obj.GetDateNow();
            var tTime=obj.GetTimeNow();
        	today=tDate;
        	totime=tTime;
        	var now = new Date();
            var hour1 = now.getHours();
            if(index=="1")
	            hour1 -= 6;            // Sub 6 hours to the time
            if(index=="2")
	            hour1 -= 12;           // Sub 12 hours to the time
            if(index=="3")
	            hour1 -= 24;           // Sub 24 hours to the time
            if(index=="4")
	            hour1 -= 48;           // Sub 48 hours to the time
            now.setHours(hour1); // Reset to new value
            
            var fDate=obj.strDate(now.getFullYear())+"-"+ obj.strDate(now.getMonth()+1)+"-"+ obj.strDate(now.getDate());
            var fTime=obj.strDate(now.getHours())+":" + obj.strDate(now.getMinutes())+":"+ obj.strDate(now.getSeconds());
            
            fromday=fDate;
            fromtime=fTime;
    	}
    	
        document.getElementById("tbl-list-review").innerHTML='<center> <span style="color:red">Loading...</span></center>';
        
		var FD=obj.Replace2(fromday);
		var TD=obj.Replace2(today);
		
		obj.SumDate(FD,TD);
		obj.SetDateCombobox();
		
		if(arrDateReview.length ==1)
		{
		    var fday=fromday + " " + fromtime;
		    var tday=today   + " " + totime;
		
		    obj.StartReview(fday,tday);
		}
		else
		{
		    var fday=arrDateReview[arrDateReview.length-1] + " 00:00:00";
		    var tday=arrDateReview[arrDateReview.length-1] + " " +totime;
		
		    obj.StartReview(fday,tday);
		}
	}
	
	obj.StartReview=function(fromday,today)
	{
	    var id=document.getElementById("selectDev").selectedIndex;
        
		obj.myMap.HideInfo();        // xoa cac Info tren ban do dang co
		obj.devTracking.ClearAll();	// xoa ban do truoc khi Xem lai
		obj.devTracking.ClearAll2();	// xoa ban do truoc khi Xem lai
		obj.devReview.ClearAll();	// xoa ban do truoc khi Xem lai
		obj.devReview.ClearLineReview(); // xóa đường Review
		if(obj.checkPlayReview==true)
		{
			obj.play(false);
		}
		
		obj.devReview.currentIndex=0;  // khoi tao lai con tro, cho no chay lai tu dau
		obj.devReview.lengthArr=0;
        
        var startPoint = document.getElementById("hdnStartPoint").value;
        
		//Call ajax here find from day to day
		xajax_ajxGetReviewList(obj.arrDevicename[id].name, obj.arrDevicename[id].id, obj.arrDevicename[id].driver, obj.arrDevicename[id].driverphone, fromday, today, startPoint);
		fromday="";
		today="";
	}
	
	
	obj.SumDate=function(FD,TD)
	{
	    var dtF = Date.parse(FD);
	    var nowdate= new Date();
	    var nD=Date.parse (nowdate);
        
		arrDateReview= new Array;
		var dtT = Date.parse(TD);
		
        if(dtT > dtF)
		{
			nSumDate = (dtT - dtF) / (24*3600000);
			    for(i = 0; i <= nSumDate; i++)
			    {
				    var dtN = dtF + i * 24 * 3600000;
                    
				    if(dtN<=nD)
				    {
				        var sdt = new Date(dtN);
				        var y = sdt.getFullYear();
				        var m = sdt.getMonth() + 1;
				        var d = sdt.getDate();
				        arrDateReview[i] = y + "-" + (m > 9 ? m : "0" + m) + "-" + (d > 9 ? d : "0" + d); 
				    }    
			    } 
		}
		else
		{
			nSumDate = 0;
			arrDateReview[0] = FD;
		}
	}	
	obj.DayChange=function()
	{
	    var index=obj.GetIndexCombobox("DateReView");
	    
	    if(arrDateReview.length>1)
	    {
	        if(index==0)
            {    	        
		        var fday=arrDateReview[0] + " " +fromtime;
		        var tday=arrDateReview[0] + " 23:59:59";
		        obj.StartReview(fday,tday);
		    }
		    else if(index==arrDateReview.length -1)
		    {
		        var fday=arrDateReview[arrDateReview.length-1] + " 00:00:00";
		        var tday=arrDateReview[arrDateReview.length-1] + " " +totime;
		        obj.StartReview(fday,tday);
		    }
		    else
		    {
		        var fday=arrDateReview[index] + " 00:00:00";
		        var tday=arrDateReview[index] + " 23:59:59";
		        obj.StartReview(fday,tday);
		    }    
		}
	}
	obj.SetDateCombobox=function()
	{
	    var strHTML="";
	    if(arrDateReview.length >1)
	    {
	        strHTML="<select name='DateReView' id='DateReView' onchange='_global.DayChange();'>"; 
	        for(i=0;i<arrDateReview.length;i++)
	        {
                if (sLang == 'vi') {
                    strHTML+="<option value="+i+" selected>"+obj.DMY2YMD(arrDateReview[i])+"</option>"
                } else { // sLang == 'en'
                    strHTML+="<option value="+i+" selected>"+arrDateReview[i]+"</option>"
                }
	        }
	        strHTML+="</select>"; 
	    }
	    document.getElementById("divDateReview").innerHTML="";
	    document.getElementById("divDateReview").innerHTML=strHTML;
	}
	obj.CheckHideChooseDevice=function()
	{
		if(obj.devReview.lengthArr>0)   // kiem tra neu co du lieu thi an Form chon thiet bi
		{
			obj.ShowChooseDevice('dvReViewTracking',false);
		}

	}	
	obj.GetIndexCombobox= function(idCom)  //tra ve Index cua Combobox
	{
	    return document.getElementById(idCom).selectedIndex;
	}
	obj.GetDateNow=function()
	{
	    var now = new Date();
        var d=obj.strDate(now.getFullYear()) + "-" + obj.strDate(now.getMonth()+1)+"-"+ obj.strDate(now.getDate());
        return d;
	}
	obj.GetTimeNow=function()
	{
	    var now = new Date();
	    var t=obj.strDate(now.getHours())+":" + obj.strDate(now.getMinutes())+":"+ obj.strDate(now.getSeconds());
	    return t;
	}
	obj.Replace= function(day)
	{   
	    var d=day.replace(/\//g,"-");
	    return d;
	}
	obj.Replace2=function(day)
	{
	    var d=day.replace(/-/g,"/");
	    return d;
	}
	obj.strDate=function(d)
    {
        if(d<10)
	        d="0"+d;
        return d;	
    }
	obj.DMY2YMD=function(day)
	{
		var arrday=day.split("-");
		var result=arrday[2]+"-"+arrday[1]+"-"+arrday[0];
		return result;
	}
	obj.CheckDay=function(day)
	{
		var result=true;
		if(typeof(day)=='undefined')
			return false;
		var arrday=day.split("-");
		if(arrday.length!=3)
			result=false;
		return result;
	}
	obj.ShowReView=function(bCheck)
	{
		for(var i in obj.devReview.arrDevice)
		{
			obj.devReview.Show(i,bCheck);
		}
	}
	obj.StringFormat=function(str)
	{		
	  for(i = 1; i < arguments.length; i++)
	  {
		str = str.replace("{" + (i-1) + "}", arguments[i]);
	  }
	  return str;		
	}	
	obj.CurrentIndex=function(index)
	{
		obj.devTracking.currentIndex=index;
	}
	obj.ShowAddress=function(nCheck)
	{
		if(nCheck==0)
		{
			for(var i in obj.devTracking.arrDevice)
			{
				if(obj.devTracking.arrDevice[i].position=="KXD")
					obj.LatLng2AddressTracking(i);
			}
		}else
		{
			for(var i in obj.devReview.arrDevice)
			{
				if(obj.devReview.arrDevice[i].position=="KXD")
					obj.LatLng2AddressReview(i);
			}
		}
	}
	obj.LatLng2AddressReview=function(index)
	{		
		 var geocoder = new GClientGeocoder();
		 var latlng=new GLatLng(obj.devReview.arrDevice[index].latitude,obj.devReview.arrDevice[index].longitude);
		var f=function showAddress(response) 
			{      
			
			  if (!response || response.Status.code != 200) {
			  } else {
				 obj.devReview.arrDevice[index].position=response.Placemark[0].address;
				 $("#tdreviewpos"+index).html(obj.devReview.arrDevice[index].position);
			  }
			}
		 try{			
			geocoder.getLocations(latlng,f);			
		 }catch(err){
		 }		
	}
	obj.LatLng2AddressTracking=function(index)
	{		
		 var geocoder = new GClientGeocoder();
		 var latlng=new GLatLng(obj.devTracking.arrDevice[index].latitude,obj.devTracking.arrDevice[index].longitude);
		var f=function showAddress(response) 
			{      
			
			  if (!response || response.Status.code != 200) {
			  } else {
				 obj.devTracking.arrDevice[index].position=response.Placemark[0].address;
				 $("#tdtracking"+index).html(obj.devTracking.arrDevice[index].position);
			  }
			}
		 try{			
			geocoder.getLocations(latlng,f);			
		 }catch(err){
		 }		
	}
    obj.HomeResize = function()
    {    
        var hdivCenter=document.getElementById("divCenter").offsetHeight;
        var hdivTabs=document.getElementById("divTabs").offsetHeight;
        var hWelcom=document.getElementById("Welcom").offsetHeight;

        var h = hdivCenter - hdivTabs - hWelcom;

        document.getElementById("MenuString").style.height = (h-10)+"px";
    } 
    
	obj.ShowCountStatus=function(run,stop,lostgps,lostgprs,buffering)
	{
		obj.arrStatus[0]=run;
		obj.arrStatus[1]=stop;
		obj.arrStatus[2]=lostgps;
		obj.arrStatus[3]=lostgprs;
        obj.arrStatus[4] = buffering;
        
		var html='<table cellpadding="1" cellspacing="0" border="0">'+
					'<tr style="height:15px" align="left" valign="middle">'+
					'<td style="width:45px;" ><input type="checkbox" name="running" id="running" value="ON"  onclick="_global.ShowDeviteCheck(0, this.checked);" ><img title="'+running+'" alt="'+running+'" src="adagps.com/images/icons/countrun.png" style="cursor:pointer"/></td>'+
					'<td style="width:10px;">:'+run+'</td>'+
					'<td style="width:45px" ><input type="checkbox" name="stopfor" id="stopfor" value="ON"  onclick="_global.ShowDeviteCheck(1, this.checked);" ><img title="'+ stopfor+'" alt="'+stopfor+'" src="adagps.com/images/icons/countstop.png" style="cursor:pointer"/></td>'+
					'<td style="width:10px;">:'+stop+'</td>'+
					'<td style="width:45px;" ><input type="checkbox" name="gpsfor" id="gpsfor" value="ON"  onclick="_global.ShowDeviteCheck(2, this.checked);" ><img title ="'+ gpsfor +'" alt="'+gpsfor +'" src="adagps.com/images/icons/countlostGPS.png" style="cursor:pointer"/></td>'+
					'<td style="width:10px;">:'+lostgps+'</td>'+
					'<td style="width:45px;" ><input type="checkbox" name="lostfor" id="lostfor" value="ON"  onclick="_global.ShowDeviteCheck(3, this.checked);" ><img title="'+lostfor +'" alt="'+ lostfor+'" src="adagps.com/images/icons/countlostGPRS.png" style="cursor:pointer"/></td>'+
					'<td style="width:10px">:'+lostgprs+'</td>'+
                    '<td style="width:45px;" ><input type="checkbox" name="buffer" id="buffer" value="ON"  onclick="_global.ShowDeviteCheck(4, this.checked);" ><img title="'+buffer +'" alt="'+ buffer+'" src="adagps.com/images/icons/countlostGPRS_green.png" style="cursor:pointer"/></td>'+
                    '<td style="width:10px">:'+buffering+'</td>'+
					'</tr>'+
				'</table>'
		document.getElementById("status-tracking").innerHTML=html;
	}
    
	obj.GetStatusCheck=function()
	{
        var arrParram=new Array();
        
        arrParram['Running'] = obj.GetCheckbox("running");
        arrParram['Stop'] = obj.GetCheckbox("stopfor");
        arrParram['LostGPS'] = obj.GetCheckbox("gpsfor"); 
        arrParram['LostGPRS'] = obj.GetCheckbox("lostfor"); 
        arrParram['SendingLog'] = obj.GetCheckbox("buffer");
        arrParram['hidHWgrid'] = document.getElementById("hidHWgrid").value; 
        return arrParram;
	}
	obj.ShowDeviteCheck=function(i,bcheck)
	{
		
		obj.arrcheckbox[i]=bcheck;
		var arrParams = obj.GetStatusCheck();
		xajax_ajxGetDeviceList(arrParams);
	}
	obj.UpdateCheckedStatus=function()
	{
		if(typeof(obj.arrcheckbox[0])!='undefined')
			$("#running").attr("checked", obj.arrcheckbox[0]);							
		if(typeof(obj.arrcheckbox[1])!='undefined')			
			$("#stopfor").attr("checked", obj.arrcheckbox[1]);	
		if(typeof(obj.arrcheckbox[2])!='undefined')			
			$("#gpsfor").attr("checked", obj.arrcheckbox[2]);	
		if(typeof(obj.arrcheckbox[3])!='undefined')			
			$("#lostfor").attr("checked", obj.arrcheckbox[3]);	
        // ĐậmPV: 2010-10-12 - Add Start
        if(typeof(obj.arrcheckbox[4]) != 'undefined')
            $('#buffer').attr('checked', obj.arrcheckbox[4]);
        // ĐậmPV: 2010-10-12 - Add End
	}
	
	function toHIS(tm)
	{
	 	try
	 	{
	 		var arr = tm.split(" ");
	 		return arr[1];
	 	}
	 	catch(e)
	 	{
	 		return tm;
	 	}
	}
	function conDee2Dec(coor, type)	//Chuyen do-phut sang so thap phan
	{
		try
		{
			var nDee = coor.substring(0, (type == "lat" ? 2 : 3));
			var nMin = coor.substring((type == "lat" ? 2 : 3), (type == "lat" ? 4 : 5)) + "." + coor.substring((type == "lat" ? 4 : 5));
			
			return parseFloat(parseFloat(nDee) + (parseFloat(nMin) / 60)).toString();
		}
		catch(e)
		{
			return (type == "lat" ? "00000000" : "000000000");
		}
	}
	function toMDYHISJS(str)
	{
		try
		{
			var arr1 = new Array();
			arr1 = str.split(" ");
			var arr2 = new Array();
			arr2 = arr1[0].toString().split("-");
            
			return arr2[1] + "/" + arr2[2] + "/" + arr2[0] + " " + arr1[1];
		}
		catch(e)
		{
			return str;
		}
	}
	function SubDateNow(time)
	{
		var arrDateTime= new Array();
		arrDateTime = time.split(" ");
		
		var arrDate= new Array();
		arrDate=arrDateTime[0].split("-");
		var arrTime= new Array();
		arrTime= arrDateTime[1].split(":");
		
		var now = new Date();		
		var timedate= new Date();
		timedate.setFullYear(arrDate[0]);
		timedate.setMonth(arrDate[1]-1); 
		timedate.setDate(arrDate[2]);
		timedate.setHours(arrTime[0]);
		timedate.setMinutes(arrTime[1]); 
		timedate.setSeconds(arrTime[2]);
		
		var diff = now.getTime( ) - timedate.getTime( );
		var diff2 = Math.floor(diff / (1000 * 60));
		
		return diff2;

	}
	obj.Sleep=function pause(millisecondi)
	{
		var now = new Date();
		var exitTime = now.getTime() + millisecondi;
		while(true)
		{
			now = new Date();
			if(now.getTime() > exitTime) return;
		}
	}
	/**
	 * Hàm gán giá trị cho 2 textbox thời gian.
	 */
	obj.SetDate=function(from, to)
	{
		//alert(from);
		document.getElementById("FromDate").value=from;
		document.getElementById("ToDate").value=to;
		
	}
	//1 V002  2010-03-09  Toannn  Thêm vào Hàm ViewPieChar vẻ biếu đồ trạng thái  Edit Start
	/**
	* Hàm Vẻ biểu đồ trạng thái xe dừng, chạy, mất GPS, mất GPRS
	*/
	obj.ViewPieChar= function()
	{	
		if(obj.indexTabBottom==2)
		{	
			if(obj.arrStatus.length>0)
			{
				xajax_ajxViewPieChar(obj.arrStatus[0],obj.arrStatus[1],obj.arrStatus[2],obj.arrStatus[3],obj.arrStatus[4]); // ĐậmPV: 2010-10-12 - Add
			}
		}
	}
	/**
	* Hàm lấy dữ liệu từ tiến obj.data được khởi tạo từ hàm ở PHP, 
	* truyền vào cho Biểu đồ hiển thị.
	*/
	obj.open_flash_chart_data=function ()
	{
		return JSON.stringify(obj.data);
	}
	//1 V002  2010-03-09  Toannn  Thêm vào Hàm ViewPieChar vẻ biếu đồ trạng thái  Edit End
    
    obj.CheckItem = function(bCheck, cbNameAll, cbNameItem) {
        if (!bCheck) {
            $('INPUT[name='+cbNameAll+']').attr('checked', false);    
            return;
        }
        
        var i = 0;
        $('INPUT[name='+cbNameItem+']').each(function(){
            if($(this).attr('checked')) {
                i++;
            }
        });
        
        var arrChecks = document.getElementsByName(cbNameItem);
        if (i == arrChecks.length) {
            $('INPUT[name='+cbNameAll+']').attr('checked', true);        
        }
    }
        obj.CallGP6000Func = function(deviceid)
    {
        obj.trackingDeviceID = deviceid;
        window.clearTimeout(obj.GP6000Timer);
        obj.GP6000Timer = 0;
        if(obj.indexGP6000 == 2)
        {
            obj.ShowDispatch();
        }
        else if(deviceid > 0)
        {
            if(obj.indexGP6000 == 1)
                obj.ShowRFID();
            else if(obj.indexGP6000 == 0)
                obj.ShowCamera();
            else
            {
                window.clearTimeout(obj.GP6000Timer);
                obj.GP6000Timer = 0;
            }
        }
    }
    obj.ShowRFID = function()
    {
        xajax_ajxShowRFID(obj.trackingDeviceID);
        obj.GP6000Timer = window.setTimeout('_global.ShowRFID()', 10000);
    }
    obj.ShowCamera = function()
    {
        xajax_ajxShowCamera(obj.trackingDeviceID);
        obj.GP6000Timer = window.setTimeout('_global.ShowCamera()', 30000);
    }
    obj.ShowDispatch = function()
    {
        xajax_ajxShowDispatch();
        obj.GP6000Timer = window.setTimeout('_global.ShowDispatch()', 5000);
    }
    obj.ShowListCamera = function(nDevID)
    {
        xajax_ajxGetSoLuong();
        xajax_ajxGetCameraList(nDevID);
        xajax_ajxGetDeviceInfo_For_Camera(nDevID); 
    }
    
    obj.PlayMediaAlert = function() {
        var url = 'sounds/alert/speed/4.mp3';
        var sScript = "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/MediaPlayer/' src='"+url+"' width='1px' height='1px' enableContextMenu='0' showstatusbar='0' autostart='1' showcontrol='0' PlayCount='1' Volume='100'/>";
        document.getElementById('dvAlertMedia').innerHTML = sScript;
    }
    
    obj.StopMediaAlert = function() {
        document.getElementById('dvAlertMedia').innerHTML = '';
    }
  
    return obj;
}
// start Trung add 
function DeleteAllLine()
{

//          for(i = Gobjpolyline.length-1;i>=0;i--){
//            var temp = Gobjpolyline.pop();            
//            Gmap.removeOverlay(temp);  
//            Gwaypoints.pop();    
//        }
        Gmap.removeOverlay(Gmarker);
        Gmarker = null;
      
   // }
          
}

function DeleteOneLine()
{    if(document.getElementById('mapType').value==0){
       var temp = Gobjpolyline.pop();
        Gmap.removeOverlay(temp);         
        Gwaypoints.pop();          
        if(Gobjpolyline.length==0){
            Gmap.removeOverlay(Gmarker);
            Gmarker=null;   
        }
        var Point = Gwaypoints[Gwaypoints.length-1];
        if(!CheckPointInView(Point)){
            Gmap.setCenter(Point);
        }
        Gpolyline = new GPolyline(Gwaypoints, 'red', 3);
        var long = Gpolyline.getLength();
        long = Math.round(long);
        var unit = $('#UnitDistance').val();                            
        long = long/unit;
        long=CurrentFormatted(long);
        document.getElementById('distanceValue').value = long; 
    }else{
        var temp = Vobjpolyline.pop();
        Vmap.removeOverlay(temp);        
        Vwaypoints.pop();           
        if(Vobjpolyline.length==0){
            Vmap.removeOverlay(Vmarker);
            Vmarker=null;   
        }
        var Point = Vwaypoints[Vwaypoints.length-1];
        if(!CheckPointInView(Point)){            
            var level= _global.myMap.GetLevel();
            Vmap.setCenter(Point,level);
        }
        Vpolyline = new VPolyline(Vwaypoints, 'red', 3);
        var long =Vpolyline.getLength();
        long = Math.round(long);
        var unit = $('#UnitDistance').val();                            
        long = long/unit;
        long=CurrentFormatted(long);
        document.getElementById('distanceValue').value = long; 
    }
}
function setFlagDistance()
{   
    if(_global.TabSelect == 0){
        if(document.getElementById('flagDistance').value==0){
             _global.StartTracking(false);
        }else{
             _global.StartTracking(true);
        }
    }else if(_global.TabSelect == 1){
         if(document.getElementById('flagDistance').value==0){
             _global.play(false);
        }
    }
    if(document.getElementById('flagDistance').value==0){
        $('#flagDistance').val(1); 
         $('#tdValue').css('display', '');
         $('#tdDeleteAll').css('display', '');
         $('#tdDeleteOne').css('display', '');
         document.getElementById('imgDistance').src='images/tracking/stop.png';
         document.getElementById('imgDistance').title="Dừng đo khoảng cách";
    }else{
         $('#flagDistance').val(0);   
         $('#tdValue').css('display', 'none');
         $('#tdDeleteAll').css('display', 'none');
         $('#tdDeleteOne').css('display', 'none');  
         document.getElementById('imgDistance').src='images/tracking/action.png'; 
         document.getElementById('imgDistance').title="Đo khoảng cách";
        DeleteAllLine();      
    }
}
function changeDisVal(){
   
    var temphdUnit = $('#hdUnitValue').val();
    temphdUnit = temphdUnit.replace(/,/g, '');
    var hdUnit = parseFloat(temphdUnit) ;    
    var tempcmbUnit = $('#UnitDistance').val();
    tempcmbUnit = tempcmbUnit.replace(/,/g, '');
    var cmbUnit =  parseFloat(tempcmbUnit) ;       
    var temptxtDisvalue = $('#distanceValue').val();    
    temptxtDisvalue = temptxtDisvalue.replace(/,/g, '');    
    var txtDisvalue = parseFloat(temptxtDisvalue) ;
    var long = txtDisvalue*hdUnit/cmbUnit;    
    long=CurrentFormatted(long);
    $('#distanceValue').val(long);
    $('#hdUnitValue').val(tempcmbUnit);
}
// ham dung de check 1 diem co nam trong khung view cua ban do hay khong
function CheckPointInView(Point){


     if(_global.checkMap==0){
         var bound =   Gmap.getBounds();
         var NorthEast = bound.getNorthEast();
         var SouthWest = bound.getSouthWest();    
      
         var srcLat = Point.lat();
         var srcLng = Point.lng();
         var NWLat = NorthEast.lat();
         var NWLng = NorthEast.lng();
         var SELat = SouthWest.lat();
         var SELng = SouthWest.lng();  
         if(srcLat<NWLat&&srcLat>SELat&&srcLng<NWLng&&srcLng>SELng){
             return true;
         }    
         return false;   
     }else{
        var bound =   Vmap.getBounds();
         var NorthWest = bound.getNorthWest();
         var SouthEast = bound.getSouthEast();
         var srcLat = Point.lat();
         var srcLng = Point.lng();
         var NWLat = NorthWest.lat();
         var NWLng = NorthWest.lng();
         var SELat = SouthEast.lat();
         var SELng = SouthEast.lng(); 
         if(srcLat<NWLat&&srcLat>SELat&&srcLng>NWLng&&srcLng<SELng){
             return true;
         }  
         return false;     
     }
}
// End Trung add